<template>
    <div>
        <el-tree
            default-expand-all
            ref="menuTreeRef"
            :data="menuTree"
            node-key="id"
            show-checkbox
            :props="defaultProps"
            :expand-on-click-node="true"
        ></el-tree>

        <el-button @click="onAuthorConfirm">确定</el-button>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { api } from '@/api/index'
const { RequestMenuAuthAll, RequestAuthorRole, RequestMenuAll } = api
let menuTree = ref([]) //菜单树
let selectMenuTree = ref([]) //选中菜单树
const menuTreeRef = ref(null)
const defaultProps = {
    children: 'children',
    label: 'label',
}
//参数:当前角色
const props = defineProps({
    currentRoleId: Number,
})
onMounted(() => {
    getMenuList()
})
/**
 * 获取菜单数据
 */
const getMenuList = () => {
    RequestMenuAll().then(data => {
        let { resultCode, resultInfo } = data
        if (resultCode === 1) {
            menuTree.value = resultInfo // 设置显示菜单树
            // 设置选中菜单树
            getMenuListByRole(props.currentRoleId)
        }
    })
}
/**
 * 当前菜单数据
 */
const getMenuListByRole = roleId => {
    RequestMenuAuthAll(roleId).then(data => {
        let { resultCode, resultInfo } = data
        if (resultCode === 1) {
            selectMenuTree.value = resultInfo
            const list = filterParentId(resultInfo)
            menuTreeRef.value.setCheckedNodes(list)
        }
    })
}

/**
 * 设置权限
 */
const onAuthorConfirm = () => {
    let selectTree = menuTreeRef.value.getCheckedNodes()
    // 根据数组id找父id，如果没有加上
    let arr = selectTree.map(item => item.id)
    arr = filterId(arr)
    let ids = arr.join(',')
    // console.log(ids)
    console.log(props.currentRoleId)
    const resType = 0 //2 按钮级资源权限，0 菜单权限
    RequestAuthorRole(props.currentRoleId, ids, resType).then(data => {
        if (data.resultCode === 1) {
            ElMessage.success('设置成功!')
        }
    })
}
/**
 * 过滤id
 */
const filterId = ids => {
    console.log('selectMenuTree.value ', menuTree.value)
    let newIds = []
    ids.forEach(id => {
        //找父id
        const subItem = menuTree.value.find(item => item.id === id)
        console.log('subItem ', subItem)
        //判断父id是否中ids数组中
        const isOk = ids.some(item => item.id === subItem?.parent_id)
        if (!isOk) {
            newIds.push(subItem.parent_id)
        }
        newIds.push(id)
    })
    return [...new Set(newIds)]
}

/**
 * 过滤父id
 */
const filterParentId = menu => {
    const list = [...menu]
    for (let i = 0; i < list.length; i++) {
        const item = list[i]
        //判断item中path是否/main开头，
        // console.log('item ',item.path);
        if (item.path.indexOf('/main') !== -1) {
            list.splice(i, 1)
            i--
        }
    }
    return list
}
</script>

<style lang="scss" scoped></style>
